package be.castanea.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Castanea
 * 2009
 * @author Geert van Leemputten, Steven Rymenans, Bart Van Hooydonck
 */
public class MessageUtil {

    public static GenericEvent decode(ByteBuffer buffer) {
        try {  
            ByteArrayInputStream bais = new ByteArrayInputStream(unwrap(buffer));
            ObjectInputStream ois = new ObjectInputStream(bais);
            GenericEvent event = (GenericEvent) ois.readObject();
            ois.close();
            return event;
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("class not found " + ex.getMessage());
        } catch (IOException ex) {
            throw new RuntimeException("io failure lim" + ex.getMessage());
        }
    }

    public static ByteBuffer encode(GenericEvent event) {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bout);

            oos.writeObject(event);
            oos.close();

            return ByteBuffer.wrap(bout.toByteArray());
        } catch (Exception ex) {
            throw new RuntimeException("could not serialize message");
        }
    }

    private static byte[] unwrap(ByteBuffer buffer) {
        List<Byte> storage = new ArrayList<Byte>();
        while (buffer.hasRemaining()) {
            storage.add(buffer.get());
        }
        byte[] message = new byte[storage.size()];
        for (int i = 0; i < storage.size(); i++) {
            message[i] = storage.get(i);
        }
        return message;
    }
}
